<?php

namespace app\home\controller;

use think\Lang;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Sellerrefund extends BaseSeller
{

    public function _initialize()
    {
        parent::_initialize();
        Lang::load(APP_PATH . 'home/lang/' . config('default_lang') . '/sellerrefund.lang.php');
        $this->getRefundStateArray();
    }

    /**
     * 退款记录列表页
     *
     */
    public function index()
    {
        $refundreturn_model = model('refundreturn');
        $condition = array();
        // $condition['store_id'] = session('store_id');
        $condition['yys_id'] = session('store_id');

        $return_type = [
            '0' => 1,
            '1' => 4
        ];
        $condition['refund_type'] = ['in', $return_type]; //类型:1为子訂單退款,2为退货,3为换货 4 大訂單退款

        $keyword_type = array('order_sn', 'refund_sn', 'buyer_name');

        $key = input('key');
        $type = input('type');

        if (trim($key) != '' && in_array($type, $keyword_type)) {
            $condition[$type] = array('like', '%' . $key . '%');
        }

        $add_time_from = input('add_time_from');
        $add_time_to = input('add_time_to');
        if (trim($add_time_from) != '' || trim($add_time_to) != '') {

            if ($add_time_from !== false || $add_time_to !== false) {
                $condition['add_time'] = array('between time', array($add_time_from, $add_time_to));
            }
        }
        $sn = intval(input('type'));


        $seller_state = intval(input('state'));
        if ($seller_state > 0) {
            $condition['seller_state'] = $seller_state;
        }
        $order_lock = intval(input('lock'));
        if ($order_lock != 1) {
            $order_lock = 2;
        }

        $refund_list = $refundreturn_model->getBigRefundList($condition, 10);
        $page = $refundreturn_model->page_info->render();

        $this->assign('refund_list', $refund_list);
        $this->assign('show_page', $page);


        /* 设置卖家当前菜单 */
        $this->setSellerCurMenu('seller_refund');
        /* 设置卖家当前栏目 */
        $this->setSellerCurItem($order_lock);

        return $this->fetch($this->template_dir . 'index');
    }

    /**
     * 退款审核页
     *
     */
    public function edit()
    {
        $refundreturn_model = model('refundreturn');
        $condition = array();
        // $condition['store_id'] = session('store_id');
        $condition['yys_id'] = session('store_id');
        $condition['refund_id'] = intval(input('param.refund_id'));
        $refund_list = $refundreturn_model->getBigRefundList($condition);

        $refund = $refund_list[0];  #获取退款的详细信息
        if (!request()->isPost()) {
            $this->assign('refund', $refund);
            $info['buyer'] = array();
            // if (!empty($refund['pic_info'])) {
            //     $info = unserialize($refund['pic_info']);
            // }
            $this->assign('pic_list', $info['buyer']);
            $member_model = model('member');
            $member = $member_model->getMemberInfoByID($refund['buyer_id']);
            $this->assign('member', $member);
            $condition = array();
            $condition['order_id'] = $refund['order_id'];
            $order = $refundreturn_model->getRightOrderList($condition, $refund['order_goods_id']);
            $this->assign('order', $order);
            $this->assign('store', $order['extend_store']);
            $this->assign('order_common', $order['extend_order_common']);
            $this->assign('goods_list', $order['goods_list']);

            //获取图片
            $apply_images = json_decode($refund['pic_info'], true);
            $this->assign('apply_images', $apply_images);
            $config = db('config')->where('code', 'qiniu_http')->find();
            $this->assign('http_name', $config['value']);

            /* 设置卖家当前菜单 */
            $this->setSellerCurMenu('seller_refund');
            /* 设置卖家当前栏目 */
            $this->setSellerCurItem('');
            return $this->fetch($this->template_dir . 'edit');
        } else {
            if ($refund['seller_state'] != '1') { //检查状态,防止页面刷新不及时造成数据错误
                ds_json_encode(10001, lang('wrong_argument'));
            }
            $order_id = $refund['order_id'];
            $refund_array = array();
            $refund_array['seller_time'] = time();
            $refund_array['seller_state'] = input('post.seller_state'); //卖家处理状态:1为待审核,2为同意,3为不同意
            $refund_array['seller_message'] = input('post.seller_message'); #审核备注
            if ($refund_array['seller_state'] == '3') {
                $refund_array['refund_state'] = '3'; //状态:1为处理中,2为待管理员处理,3为已完成
                //先判断当前订单是不是大订单退款
                if ($refund['refund_type'] == 4) {
                    //大订单的话修改为无状态
                    db('app_order')->where(['app_order_id' => $refund['app_order_id']])->update(['refund_price' => 0]);
                    //找个所有的子订单 改为无退款
                    $app_order_info = db('app_order')->where(['app_order_id' => $refund['app_order_id']])->find();
                    $order_ids = explode(',', $app_order_info['order_ids']);
                    foreach ($order_ids as $key => $value) {
                        db('order')->where(['order_id' => $value])->update(['refund_state' => 0]);
                    }
                    //删除数据
                    db('refundreturn')->where(['refund_id' => $condition['refund_id']])->update(['return_del' => 1]);
                } else {
                    //子订单退款不同意的话直接修改状态
                    db('ordergoods')->where(['order_id' => $order_id])->update(['fail_status' => 1]); //状态:0：无操作 1：退款失败 2：退货失败 3：换货失败
                    db('ordergoods')->where(['order_id' => $order_id])->update(['return_status' => 0]);
                    db('refundreturn')->where(['order_id' => $order_id])->update(['return_del' => 1]);
                }
            } else {
                //同意的话
                if (!empty($refund['app_order_id'])) {
                    //修改大订单退款状态 用于判断后台退款按钮
                    db('app_order')->where(['app_order_id' => $refund['app_order_id']])->data(['order_status' => '4', 'audit_refund' => 0])->update();
                }
                $refund_array['seller_state'] = '2';
                $refund_array['refund_state'] = '2';
            }
            $state = $refundreturn_model->editRefundreturn($condition, $refund_array);
            if ($state) {
                #根据运营商审核的状态，给客户推送消息 
                $member_info = db('member')
                    ->where(['member_id' => $refund['buyer_id']])
                    ->find();

                #通知内容
                $notif_data = [
                    'order_id' => $order_id,
                    'notif_title' => '退款通知',
                    'notif_content' =>  '提交的退款申请已审核，审核备注：' . $refund_array['seller_message'],
                    'member_id' => $member_info['member_id'],
                    'member_name' => $member_info['member_name'],
                ];
                model('points')->saveAfficeslog(0, 0, $notif_data); #客户
                if ($refund_array['seller_state'] == 2 && $refund['refund_type'] !=4) {
                    #运营商审核通过之后，会给供应商、客户都发通知   (大订单退款不需要平台审核，运营商审核之后就可以了)
                    model('points')->saveAfficeslog(0, 3, $notif_data); #供应商
                } 
                #推送
                pushMessageToSingle('通知', $member_info['clientid'], '您提交的退款申请已审核，请及时查看！');
                #end


                if ($refund_array['seller_state'] == '3' && $refund['order_lock'] == '2') {
                    $refundreturn_model->editOrderUnlock($order_id); //订单解锁
                }
                $this->recordSellerlog(lang('refund_processing') . $refund['refund_sn']);


                #退款的话无需后台审核 直接通过
                if ($refund_array['seller_state'] == 2) {
                    if (!isset($refund['app_order_id'])) {
                        #order
                        $order_info = db('order')->where("order_id", $refund['order_id'])->find();
                        $order_ids = array();
                        $order_ids['0'] = $order_info['order_id'];
                        $ordergoods_ids = db('ordergoods')->where("order_id", $refund['order_id'])->filed('rec_id')->select();
                    } else {
                        #app_order
                        $app_order_info = db('app_order')->where("app_order_id", $refund['app_order_id'])->find();
                        $order_ids = explode(',', $app_order_info['order_ids']);
                        $ordergoods_ids = explode(',', $app_order_info['ordergoods_ids']);
                    }
                    foreach ($order_ids as $k => $v) {
                        db('order')->where('order_id', $v)->data(['refund_state' => '3', 'order_state' => '0'])->update();
                    }
                    foreach ($ordergoods_ids as $k => $v) {
                        db('ordergoods')->where('rec_id', $v)->data(['return_status' => '6'])->update();
                    }
                    //更新退款表  改为已完成
                    db('refundreturn')->where(['refund_id' => $refund['refund_id']])->update(['refund_state' => 3]);

                    #判断是否使用优惠券  使用的话 退单返回优惠券
                    if (isset($app_order_info) && $app_order_info['voucher_id']) {
                        $coupon_info = db('voucher_collection')->where(['member_id' => $app_order_info['user_id'], 'voucher_id' => $app_order_info['voucher_id'], 'is_used' => 2, 'is_send_del' => 0])->find();
                        if ($coupon_info) {
                            db('voucher_collection')->where(['id' => $coupon_info['id']])->data(['is_used' => 1, 'used_time' => ''])->update();
                        }
                    }/*else {   使用不了 因为只是退小订单的话 优惠券还存在部分使用的情况
                        if ($order_info['order_voucher']) {
                            $app_order_info = db('app_order')->where("app_order_id", $order_info['apporder_id'])->find();
                            if ($app_order_info['voucher_id']) {
                                $coupon_info = db('voucher_collection')->where(['member_id' => $app_order_info['user_id'], 'voucher_id' => $app_order_info['voucher_id'], 'is_used' => 1, 'is_send_del' => 0])->find();
                                if ($coupon_info) {
                                    db('voucher_collection')->where(['id' => $coupon_info['id']])->data(['is_used' => 0, 'used_time' => ''])->update();
                                }
                            }
                        }
                    }*/
                }
                // 发送买家消息
                $param = array();
                $param['code'] = 'refund_return_notice';
                $param['member_id'] = $refund['buyer_id'];
                $param['param'] = array(
                    'refund_url' => url('Memberrefund/view/', ['refund_id' => $refund['refund_id']]),
                    'refund_sn' => $refund['refund_sn']
                );
                \mall\queue\QueueClient::push('sendMemberMsg', $param);
                ds_json_encode(10000, lang('ds_common_save_succ'));
            } else {
                ds_json_encode(10001, lang('ds_common_save_fail'));
            }
        }
    }

    /**
     * 主商品详情页
     */
    public function return_view()
    {
        if (request()->isPost()) {
        } else {
            $config = db('config')->where('code', 'qiniu_http')->find();
            $this->assign('http_name', $config['value']);
            $commonid = input('param.commonid');
            $goods = db('y_goods')->where(['goods_commonid' => $commonid])->find();
            $this->view->goods = $goods;
            $this->assign('commonids', $commonid);
            $goods_info = db('goodscommon')->where(['goods_commonid' => $commonid])->find();

            $goods = db('goods')->where(['goods_commonid' => $commonid])->select();
            //获取价格
            foreach ($goods as $k => $v) {
                if ($v['t_type'] == 0) {
                    $goods[$k]['t_price'] = '未设置';
                    $goods[$k]['g_price'] = '未设置';
                } else {
                    if ($v['t_type'] == 1) {
                        $goods[$k]['t_price'] = $v['goods_price'] + $v['goods_price'] * $v['t_value'] / 100 + $v['freight'];
                    } elseif ($v['t_type'] == 2) {
                        $goods[$k]['t_price'] = $v['goods_price'] + $v['t_value'] + $v['freight'];
                    }
                    if ($v['g_type'] == 1) {
                        $goods[$k]['g_price'] = $v['goods_price'] + $v['goods_price'] * $v['g_value'] / 100 + $v['freight'];
                    } elseif ($v['g_type'] == 2) {
                        $goods[$k]['g_price'] = $v['goods_price'] + $v['g_value'] + $v['freight'];
                    }
                }
            }
            $this->assign('goods', $goods);
            if (empty($goods_info['files'])) {
                $goods_info['files_info'] = '';
            } else {
                $goods_info['files_info'] = json_decode($goods_info['files'], true);
                $goods_info['files_info']['old_file_name'] = explode(',', $goods_info['files_info']['old_file_name']);
                $goods_info['files_info']['new_file_name'] = explode(',', $goods_info['files_info']['new_file_name']);
            }
            //p($goods_info);die;
            $this->assign('goods_info', $goods_info);

            $goods_img = db('goodsimages')->where(['goods_commonid' => $commonid])->select();
            $this->assign('goods_img', $goods_img);

            //获取运营商身份
            $store_id = session('store_id');

            $where = [
                'store_id' => $store_id
            ];
            $member = model('store')->where($where)->find();
            $this->assign('member_type', $member['supplier_type']);

            //获取价格


            return $this->fetch($this->template_dir . 'store_goods_detail');
        }
    }

    /**
     * 退款进度查看页
     *
     */
    public function view()
    {
        $refundreturn_model = model('refundreturn');
        $condition = array();
        // $condition['store_id'] = session('store_id');
        $condition['yys_id'] = session('store_id');
        $condition['refund_id'] = intval(input('param.refund_id'));
        $refund_list = $refundreturn_model->getBigRefundList($condition);
        $refund = $refund_list[0];
        $this->assign('refund', $refund);
        $info['buyer'] = array();


        $this->assign('pic_list', $info['buyer']);
        $member_model = model('member');
        $member = $member_model->getMemberInfoByID($refund['buyer_id']);
        $this->assign('member', $member);
        $condition = array();
        $condition['order_id'] = $refund['order_id'];
        $order = $refundreturn_model->getRightOrderList($condition, $refund['order_goods_id']);
        $this->assign('order', $order);
        $this->assign('store', $order['extend_store']);
        $this->assign('order_common', $order['extend_order_common']);
        $this->assign('goods_list', $order['goods_list']);

        //获取图片
        $apply_images = json_decode($refund['pic_info'], true);
        $this->assign('apply_images', $apply_images);
        $config = db('config')->where('code', 'qiniu_http')->find();
        $this->assign('http_name', $config['value']);

        /* 设置卖家当前菜单 */
        $this->setSellerCurMenu('seller_refund');
        /* 设置卖家当前栏目 */
        $this->setSellerCurItem('');
        return $this->fetch($this->template_dir . 'view');
    }

    function getRefundStateArray($type = 'all')
    {
        $state_array = array(
            '1' => lang('refund_state_confirm'),
            '2' => lang('refund_state_yes'),
            '3' => lang('refund_state_no')
        ); //卖家处理状态:1为待审核,2为同意,3为不同意
        $this->assign('state_array', $state_array);

        $type_array = array(
            '1' => '退款',
            '2' => '退货',
            '3' => '换货'
        ); //卖家处理状态:1为待审核,2为同意,3为不同意
        $this->assign('type_array', $type_array);

        $admin_array = array(
            '1' => lang('in_processing'),
            '2' => '平台待退款',
            '3' => lang('has_been_completed')
        ); //确认状态:1为买家或卖家处理中,2为待平台管理员处理,3为退款退货已完成
        $this->assign('admin_array', $admin_array);

        $state_data = array(
            'seller' => $state_array,
            'admin' => $admin_array
        );
        if ($type == 'all') {
            return $state_data; //返回所有
        }
        return $state_data[$type];
    }

    /**
     * 用户中心右边，小导航
     *
     * @param string $menu_type 导航类型
     * @param string $menu_key 当前导航的menu_key
     * @return
     */
    function getSellerItemList()
    {
        $menu_array = array(
            array(
                'name' => '2',
                'text' => '退款列表',
                'url' => url('Sellerrefund/index', ['lock' => 2])
            ),
            // array(
            //     'name' => '1',
            //     'text' => lang('after_refund'),
            //     'url' => url('Sellerrefund/index',['lock'=>1])
            // ),
        );
        return $menu_array;
    }


    /*
   大订单获取小订单列表
  */
    public function order_list()
    {
        $order_id = intval(input('param.order_id'));
        // echo $order_id;die;
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }
        $app_order_info = db('app_order')->where('app_order_id', $order_id)->where('is_cancel', '0')->find();
        // p($app_order_info);die;
        if (empty($app_order_info)) {
            $this->error('操作失败');
        }
        if ($app_order_info['invoice_status'] != '0') {
            $invoice_info = db('invoice')->where('app_order_id', $order_id)->find();
            $this->assign('invoice_info', $invoice_info);
            $this->assign('app_order_info', $app_order_info);
        }

        $order_list = db('order')->where('order_id', 'in', $app_order_info['order_ids'])->select();
        // p($app_order_info);die;
        if (empty($order_list)) {
            $this->error('操作失败');
        }
        $this->assign('order_list', $order_list);
        //        return $this->fetch('order_list');
        /* 设置卖家当前菜单 */
        $this->setSellerCurMenu('seller_refund');
        /* 设置卖家当前栏目 */
        //        $this->setSellerCurItem($order_lock);
        return $this->fetch($this->template_dir . 'order_list');
    }

    /**
     * 查看订单
     *
     */
    public function show_order()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }
        $order_model = model('order');
        $order_info = $order_model->getOrderInfo(array('order_id' => $order_id), array('order_goods', 'order_common', 'store'));

        //订单变更日志
        $log_list = $order_model->getOrderlogList(array('order_id' => $order_info['order_id']));
        $this->assign('order_log', $log_list);

        //退款退货信息
        $refundreturn_model = model('refundreturn');
        $condition = array();
        $condition['order_id'] = $order_info['order_id'];
        $condition['seller_state'] = 2;
        // $condition['admin_time'] = array('gt', 0);
        $return_list = $refundreturn_model->getReturnList($condition);
        $this->assign('return_list', $return_list);

        //退款信息
        $refund_list = $refundreturn_model->getRefundList($condition);
        $this->assign('refund_list', $refund_list);

        //卖家发货信息
        if (!empty($order_info['extend_order_common']['daddress_id'])) {
            $daddress_info = model('daddress')->getAddressInfo(array('daddress_id' => $order_info['extend_order_common']['daddress_id']));
            $this->assign('daddress_info', $daddress_info);
        }
        $this->assign('order_info', $order_info);
        $this->setSellerCurMenu('seller_refund');
        /* 设置卖家当前栏目 */
        //        $this->setSellerCurItem($order_lock);
        return $this->fetch($this->template_dir . 'show_order');
    }
}
